$(document).ready(function() {
	var label = new Label();
	var gDestoutObj="";
	var dn_cnt_a=0;
    var VAL ={
        NORMAL     : "0000000"  ,
        T_XPWMSOPE : "XPWMSOPE" ,
        T_XPAPLYWO : "XPAPLYWO" ,
        T_XPINQBOX : "XPINQBOX" ,
        T_XPAPLYDN : "XPAPLYDN" ,
        T_XPINQCOD : "XPINQCOD",
        T_XPINQPALT : "XPINQPALT",
        EVT_USER   : $("#userId").text()
    };
    var domObj = {
		$window : $(window),
		$woInfoGrdDiv : $("#woInfoGrdDiv"),
		$woInfoGrd : $("#woInfoGrd"),
		$ppboxInfoGrdDiv : $("#ppboxInfoGrdDiv"),
		$ppboxInfoGrd : $("#ppboxInfoGrd")
	};
  //  var _isDnFirst = true;

    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                : $(window),
       // $dnPriorityRadio : $('#dnPriorityRadio'),
       // $woPriorityRadio : $('#woPriorityRadio'),
        $vdrIDSelect     : $('#vdrIDSelect'),
        $DNNoSelect      : $('#DNNoSelect'),
        $woIdSelect      : $('#woIdSelect'),
        $destShopSelect  : $('#destShopSelect'),
        $DNNoSp          : $('#DNNoSp'),
        $ppBoxIDInput    : $('#ppBoxIDInput'),
        $shipboxInput    : $('#shipboxInput'),
     //   $palletInput    : $('#palletInput'),
        $palletIDInput   : $('#palletIDInput'),
        $phypalletIDInput: $('#phypalletIDInput'),
        $trxUserInput    : $('#trxUserInput'),
        $palteNOInput    : $('#palteNOInput'),
        $remarkInput     : $('#remarkInput'),
      //  $soSIDDiv        : $('#soSIDDiv'),
      //  $soSIdSelect     : $('#soSIdSelect'),
       print1Select      : $("#print1Select"),
        woInfoGrd : {
            $grdId     : $("#woInfoGrd"),
            grdPg      : "#woInfoPg",
            $fatherDiv : $("#woInfoGrdDiv")
        },
        mainGrd : {
            $grdId     : $("#ppboxInfoGrd"),
            grdPg      : "#ppboxInfoPg",
            $fatherDiv : $("#ppboxInfoGrdDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        $query_btn  : $('#query_btn'),
        $clear_btn  : $('#clear_btn'),
        $wh_out_btn : $('#wh_out_btn'),
        $addWoBtn   : $('#addWoBtn'),
        $del_wo_btn : $('#del_wo_btn'),
 //       $autobtn    : $('#autobtn'),
        $pack_btn   : $('#pack_btn'),
        $unpack_btn : $('#unpack_btn')
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        clearInput : function(){
            controlsQuery.$DNNoSp.text("");
            controlsQuery.$ppBoxIDInput.val("");
            controlsQuery.$shipboxInput.val("");
            controlsQuery.$palletIDInput.val("");
           // controlsQuery.$palletInput.val("");
           controlsQuery.$phypalletIDInput.val("");
            controlsQuery.$remarkInput.val("");
            $("#sohideDiv").hide();
        },
        iniuserSelect : function(){
            var inTrxObj,
                outTrxObj;
            inTrxObj = {
                trx_id      : 'XPLSTDAT' ,
                action_flg  : 'Q'        ,
                iary        : {
                    data_cate : "CYRY"//承运人员
                }
            };
            outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(outTrxObj.rtn_code == VAL.NORMAL){
                _setSelectDate(outTrxObj.tbl_cnt, outTrxObj.oary, "data_ext", "data_ext", "#trxUserInput", true);
            }
        },
        inipalteSelect : function(){
            var inTrxObj,
                outTrxObj;
            inTrxObj = {
                trx_id      : 'XPLSTDAT' ,
                action_flg  : 'Q'        ,
                iary        : {
                    data_cate : "CPHM"//车牌号码
                }
            };
            outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(outTrxObj.rtn_code == VAL.NORMAL){
                _setSelectDate(outTrxObj.tbl_cnt, outTrxObj.oary, "data_ext", "data_ext", "#palteNOInput", true);
            }
        },
        iniVdrIDSelect : function(){
            var inTrxObj,
                outTrxObj;
            inTrxObj = {
                trx_id      : 'XPLSTDAT' ,
                action_flg  : 'Q'        ,
                iary        : {
                    data_cate : "CUSD"
                }
            };
            outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(outTrxObj.rtn_code == VAL.NORMAL){
                if(1 < parseInt(outTrxObj.tbl_cnt, 10)){
                    outTrxObj.oary.sort(function(x, y){
                        if(x.data_item < y.data_item){
                            return -1;
                        }else if(x.data_item > y.data_item){
                            return 1;
                        }else{
                            return 0;
                        }
                    });
                }
                _setSelectDate(outTrxObj.tbl_cnt, outTrxObj.oary, "data_item", "data_item", "#vdrIDSelect",true);
            }
        },
        /**
         * 筛选出用户可以操作的仓位 By THY
         */
        setDestShopSel : function(){
        	var inObj;
        	var iary={
        		data_cate : 'DEST',
        		data_ext  : "'F','E'",
        		user_id   : VAL.EVT_USER
        	};
        	inObj = {
			   trx_id     : 'XPLSTDAT' ,
	           action_flg : 'F'        ,
	           iary       : iary
        	};
        	gDestoutObj = comTrxSubSendPostJson(inObj);
        	if(gDestoutObj.rtn_code == VAL.NORMAL){
        		_setSelectDate(gDestoutObj.tbl_cnt,gDestoutObj.oary,"data_id","data_desc","#destShopSelect",true);
        	}
        },
        /**
         * 获取对象中指定属性的全部值数组（有任何一项属性不存在则返回空数组）
         * @param obj 要检查的对象
         * @param property 属性数组
         * @returns {Array}
         */
        getOwnProperty : function(obj, property){
            var i,
                property_cnt = property.length,
                values = [];
            for(i = 0; i < property_cnt; i++){
                if(obj.hasOwnProperty(property[i])){
                    values.push(obj[property[i]]);
                }else{
                    console.warn('Not found property [%s].', property[i]);
                    return [];
                }
            }
            return values;
        },
        /**
         * 给select赋值，value和text均为多项属性的组合
         * @param $selectObj
         * @param dataArr
         * @param firstSpace
         * @param valueProperty
         * @param textProperty
         * @param valueSeparator
         * @param textSeparator
         * @returns {boolean}
         */
        setSelectDataWithManyText : function($selectObj, dataArr, firstSpace,
                                             valueProperty, textProperty, valueSeparator, textSeparator ){
            var i,
                realCnt,
                tmpHtml,
                tmpVals = [],
                tmpTexts = [],
                finalValueSeparator = valueSeparator || '@',
                finalTextSeparator = textSeparator || '-';
            //Check input
            if(!$.isArray(dataArr)){
                console.error('dataArr [%s] must be array!', dataArr);
                return false;
            }
            if(!$.isArray(valueProperty)){
                console.error('valueProperty [%s] must be array!', valueProperty);
                return false;
            }
            if(!$.isArray(textProperty)){
                console.error('textProperty [%s] must be array!', textProperty);
                return false;
            }
            $selectObj.empty();
            realCnt = parseInt(dataArr.length, 10);
            if(firstSpace === true){
            	$selectObj.append("<option></option>");
            }
            for( i = 0; i < realCnt; i++ ){
                tmpVals = toolFunc.getOwnProperty(dataArr[i], valueProperty);
                tmpTexts = toolFunc.getOwnProperty(dataArr[i], textProperty);
                if(tmpVals.length > 0 &&
                    tmpTexts.length > 0){
                	$selectObj.append("<option value='"+tmpVals.join(finalValueSeparator)+"'>"+tmpTexts.join(finalTextSeparator) + "</option>");
                }
            }

            $selectObj.select2({
    	    	theme : "bootstrap"
    	    });
            return true;
        },
        setSelectDataWithManyTextfordn : function($selectObj, dataArr, firstSpace,
                valueProperty, textProperty, valueSeparator, textSeparator ){
        	var i,
        		realCnt,
                tmpHtml,
                tmpVals = [],
                tmpTexts = [],
                finalValueSeparator = valueSeparator || '@',
                finalTextSeparator = textSeparator || '-';
            //Check input
        	if(!$.isArray(dataArr)){
                console.error('dataArr [%s] must be array!', dataArr);
                return false;
            }
            if(!$.isArray(valueProperty)){
                console.error('valueProperty [%s] must be array!', valueProperty);
                return false;
            }
            if(!$.isArray(textProperty)){
            	console.error('textProperty [%s] must be array!', textProperty);
            	return false;
            }
            
            $selectObj.empty();
            realCnt = parseInt(dataArr.length, 10);
            if(firstSpace === true){
                $selectObj.append("<option></option>");
            }
            for( i = 0; i < realCnt; i++ ){
                tmpVals = toolFunc.getOwnProperty(dataArr[i], valueProperty);
                tmpTexts = toolFunc.getOwnProperty(dataArr[i], textProperty);
                tmpVals.push(i+1);
                if(tmpVals.length > 0 &&
                        tmpTexts.length > 0){
                   // $selectObj.append("<option value='"+tmpVals.join(finalValueSeparator)+"'>"+tmpTexts.join(finalTextSeparator) + "</option>");
                    $selectObj.append("<option value='"+tmpVals.join(finalValueSeparator)+"'>"+tmpTexts + "</option>");
                }
            }
            $selectObj.select2({
    	    	theme : "bootstrap"
    	    });
            return true;
        },
//        getDnwoPriorityRadiosCheckValue : function(){
//            return $('input[name=dnwoPriorityRadios]:checked').attr('value');
//        },
//        dnwoPriorityRadiosClick : function(){
//            btnQuery.$clear_btn.click();
//            controlsQuery.$woIdSelect.empty();
//            controlsQuery.$DNNoSelect.empty();
//            switch(toolFunc.getDnwoPriorityRadiosCheckValue()){
//                case 'dn':
//                    console.log('By dn');
//                    _isDnFirst = true;
//                    toolFunc.setDnIdSelect();
//                    controlsQuery.$soSIDDiv.hide();
//                    break;
//                case 'wo' :
//                    console.log('By wo');
//                    _isDnFirst = false;
//                //    toolFunc.setSoSIdSelect();
//                    controlsQuery.$soSIDDiv.show();
//                    toolFunc.setWoIdSelect()
//                    break;
//                default:
//                    break;
//            }
//        },
        setDnIdSelect : function(woId){
            "use strict";
            var i,
                inObj,
                outObj,
                iary = {},
                dn_cnt,
                cus_id,
                dn_arr = [],
                final_dn_arr = [],
                tmp_dn_no;
   //         var actionflg = 'Q';
            cus_id = controlsQuery.$vdrIDSelect.val();
            iary.cus_id = cus_id;
            if(woId){
                iary.wo_id_fk = woId;
            }
            /**
             * list出WAIT状态的DN
             */
            iary.dn_stat = "WAIT";
//            if(_isDnFirst){
 //           	actionflg = 'G';
//            }
            inObj = {
                trx_id      : VAL.T_XPAPLYDN,
                action_flg  : 'G',
                iary        : iary
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                dn_cnt = parseInt(outObj.tbl_cnt, 10);
                if(dn_cnt === 0){
                    controlsQuery.$DNNoSelect.empty();
                    return true;
                }else if(dn_cnt === 1){
                    dn_arr.push(outObj.oary);
                }else if(dn_cnt > 1){
                    dn_arr = outObj.oary;
                }else{
                    console.warn('dn count %s invalid', dn_cnt);
                    return false;
                }
                dn_cnt_a = dn_cnt;
                dn_arr.sort(function (a, b) {
                    if (a.plan_timestamp < b.plan_timestamp)
                        return -1;
                    if (a.plan_timestamp > b.plan_timestamp)
                        return 1;
                    return 0;
                });
//                toolFunc.setSelectDataWithManyTextfordn(controlsQuery.$DNNoSelect,
//                		dn_arr, true, ['dn_no','evt_seq_id','plan_timestamp'], ['dn_no', 'plan_timestamp']);
                toolFunc.setSelectDataWithManyTextfordn(controlsQuery.$DNNoSelect,
                		dn_arr, true, ['dn_no'], ['dn_no']);
                controlsQuery.$DNNoSelect.select2({
                	theme : "bootstrap"
                });
            }
            return true;
        },
        setWoIdSelect : function(dnId){
            "use strict";
            var inObj,
                outObj,
                iary = {},
                cus_id,
            //    so_id,
                action_flg = 'Q',
                wo_cnt,
                wo_arr = [],
                outObjWo;
            cus_id = controlsQuery.$vdrIDSelect.val();
            iary = {
                cus_id  : cus_id
            };
            var dninfo = new Array();
            if(dnId){
            	dninfo = dnId.split("@");
                iary.dn_no = dninfo[0];
//                var datetimeinfo = new Array();
//                datetimeinfo = dninfo[2].split(" ");
//                iary.date = datetimeinfo[0];
//                var time1 = datetimeinfo[1];
//                var time1info = new Array();
//                time1info = time1.split(".");
//                iary.time = time1info[0];
                action_flg = 'Q';
            }
            inObj = {
                trx_id      : VAL.T_XPAPLYDN,
                action_flg  : action_flg    ,
                iary        : iary
            };
          //  so_id = controlsQuery.$soSIdSelect.val();
//            if (so_id){
//            	inObj.so_id = so_id;
//            }
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
//                if('T' === action_flg){
//                    outObjWo = outObj.table;
//                }else if('Q' === action_flg){
//                    outObjWo = outObj.oary;
//                }
                outObjWo = outObj.oary;
                wo_cnt = parseInt(outObj.tbl_cnt, 10);
                if(wo_cnt === 0){
                    controlsQuery.$woIdSelect.empty();
                    return true;
                }else if(wo_cnt === 1){
                    wo_arr.push(outObjWo);
                }else if(wo_cnt > 1){
                    wo_arr = outObjWo;
                }else{
                    console.warn('wo count %s invalid', wo_cnt);
                    return false;
                }
//                if (so_id){
//                	wo_arr.sort(function (a, b) {
//                        if (a.pln_stb_timestamp < b.pln_stb_timestamp)
//                            return -1;
//                        if (a.pln_stb_timestamp > b.pln_stb_timestamp)
//                            return 1;
//                        return 0;
//                    });
//                    toolFunc.setSelectDataWithManyText(controlsQuery.$woIdSelect,
//                        wo_arr, true, ['wo_id'], ['wo_id', 'pln_stb_timestamp']);
//                }else {
//                	wo_arr.sort(function (a, b) {
//                        if (a.act_stb_timestamp < b.act_stb_timestamp)
//                            return -1;
//                        if (a.act_stb_timestamp > b.act_stb_timestamp)
//                            return 1;
//                        return 0;
//                    });
//                    toolFunc.setSelectDataWithManyText(controlsQuery.$woIdSelect,
//                        wo_arr, true, ['wo_id'], ['wo_id', 'act_stb_timestamp']);
//                }
//            	wo_arr.sort(function (a, b) {
//                    if (a.act_stb_timestamp < b.act_stb_timestamp)
//                        return -1;
//                    if (a.act_stb_timestamp > b.act_stb_timestamp)
//                        return 1;
//                    return 0;
//                });
                toolFunc.setSelectDataWithManyText(controlsQuery.$woIdSelect,
                    wo_arr, true, ['wo_id_fk'], ['wo_id_fk']);
            }
            return true;
        },
        
//        setSoSIdSelect : function (){
//            "use strict";
//            controlsQuery.$soSIdSelect.empty();
//            var inObj,
//                outObj,
//                iary = {},
//                cus_id,
//                action_flg = 'Q',
//                wo_cnt,
//                wo_arr = [],
//                outObjWo;
//            cus_id = controlsQuery.$vdrIDSelect.val();
//            iary = {
//                cus_id  : cus_id,
//                wo_typ  : "S",
//                wo_stats : "'WAIT','CLOS'"
//            };
//            inObj = {
//                trx_id      : VAL.T_XPAPLYWO,
//                action_flg  : action_flg    ,
//                iary        : iary
//            };
//            outObj = comTrxSubSendPostJson(inObj);
//            if (outObj.rtn_code == VAL.NORMAL) {
//                if('T' === action_flg){
//                    outObjWo = outObj.table;
//                }else if('Q' === action_flg){
//                    outObjWo = outObj.oary;
//                }
//                wo_cnt = parseInt(outObj.tbl_cnt, 10);
//                if(wo_cnt === 0){
//                    controlsQuery.$woIdSelect.empty();
//                    return true;
//                }else if(wo_cnt === 1){
//                    wo_arr.push(outObjWo);
//                }else if(wo_cnt > 1){
//                    wo_arr = outObjWo;
//                }else{
//                    console.warn('wo count %s invalid', wo_cnt);
//                    return false;
//                }
//                wo_arr.sort(function (a, b) {
//                    if (a.pln_stb_timestamp < b.pln_stb_timestamp)
//                        return -1;
//                    if (a.pln_stb_timestamp > b.pln_stb_timestamp)
//                        return 1;
//                    return 0;
//                });
//                toolFunc.setSelectDataWithManyText(controlsQuery.$soSIdSelect,
//                    wo_arr, true, ['so_id'], ['so_id', 'pln_stb_timestamp']);
//            }
//            return true;
//        },
       printPallet : function(iary){
       	if(iary.length == 0){
       		return false;
       	}
       	showMessengerSuccessDialog("正在打印栈板标签...",1);
       	var inObj = {
           	trx_id      : VAL.T_XPINQPALT,
               action_flg  : "P",
               iary        : iary
           };
       	var outObj = comTrxSubSendPostJson(inObj);
       	if(outObj.rtn_code == VAL.NORMAL){
       		var oary = outObj.pallet_cnt > 1 ? outObj.oary : [outObj.oary];
       		var mdlCate = [],mdlId = [],count = [],dnNo = [],cusInfoFst = [],cusInfoSnd = [],
       			palletId = [],boxIds = [];
       		for(var i=0; i<outObj.pallet_cnt; i++){
       			if(oary[i].mdl_cate.length == 0){
       				mdlCate[i] = "";
       			}else{
       				mdlCate[i] = oary[i].mdl_cate;
       			}

       			if(oary[i].mdl_id.length == 0){
       				mdlId[i] = "";
       			}else{
       				mdlId[i] = oary[i].mdl_id;
       			}

       			count[i] = oary[i].count;

       			if(oary[i].dn_no.length == 0){
       				dnNo[i] = "";
       			}else{
       				dnNo[i] = oary[i].dn_no;
       			}

       			if(oary[i].cus_info_fst.length == 0){
       				cusInfoFst[i] = "";
       			}else{
       				cusInfoFst[i] = oary[i].cus_info_fst;
       			}

       			if(oary[i].cus_info_snd.length == 0){
       				cusInfoSnd[i] = "";
       			}else{
       				cusInfoSnd[i] = oary[i].cus_info_snd;
       			}

       			if(oary[i].pallet_id.length == 0){
       				palletId[i] = "";
       			}else{
       				palletId[i] = oary[i].pallet_id;
       			}

       			boxIds[i] = oary[i].boxIds;
       		}
       		var printObj = {
  					stdQty      : outObj.pallet_cnt,
  					mdlCateAry     : mdlCate,
  					mdlIdAry       : mdlId,
  					countAry       : count,
  					dnNoAry        : dnNo,
  					cusInfoFstAry  : cusInfoFst,
  					cusInfoSndAry  : cusInfoSnd,
  					palletIdAry    : palletId,
  					boxIdsAry      : boxIds
  			   	};
      			// label.PrintWhout(controlsQuery.print1Select.find("option:selected").text(),JSON.stringify(printObj));
                label.PrintpalforHX(controlsQuery.print1Select.find("option:selected").text(), mdlId[0],boxIds[0].split("、").length, count[0],palletId[0],"201706");
       	}
       },
        //获取打印机
       getPrinters : function(){
       	controlsQuery.print1Select.append("<option ></option>");
       	if (printers !== undefined) {
       		for(var i=0; i<printers.length; i++){
               	controlsQuery.print1Select.append("<option>"+ printers[i] +"</option>");
           	}
			}
       	controlsQuery.print1Select.select2({
   	    	theme : "bootstrap"
   	    });
       },
    };

    function isArray(o){
        return Object.prototype.toString.call(o)=='[object Array]';
    }

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        query_func : function(){
            var inObj,
                outObj,i,
                wo_ids = [],
                wo_info_grid,
                wo_info_grid_ids,
                rowDatas = [];
            inObj = {
                trx_id      : VAL.T_XPINQBOX,
                action_flg  : 'I'           ,
                box_stat    : 'SHIP'        
            };
            if (controlsQuery.$destShopSelect.val() !== ""){
            	inObj.dest_shop = controlsQuery.$destShopSelect.val();
            }
            if (controlsQuery.$vdrIDSelect.val() !== ""){
            	inObj.cus_id = controlsQuery.$vdrIDSelect.val();
            }
//            if ( !_isDnFirst && controlsQuery.$soSIdSelect.val() !== ""){
//            	inObj.so_id = controlsQuery.$soSIdSelect.val();
//            }
            wo_info_grid = controlsQuery.woInfoGrd.$grdId;
            wo_info_grid_ids = wo_info_grid.jqGrid('getDataIDs');
            if(wo_info_grid_ids.length > 0){
                for(i = wo_info_grid_ids.length -1; i >= 0; i--){
                    wo_ids.push(wo_info_grid.jqGrid('getRowData', wo_info_grid_ids[i])['wo_id']);
                }
                inObj.wo_ids = "'" + wo_ids.join("','") + "'";
            }
            if(controlsQuery.$woIdSelect.val()){
            	inObj.wo_id = controlsQuery.$woIdSelect.val();
            }
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                oary = _destListTool.addDestDesc(outObj.box_info,
                    'dest_shop', null, 'dest_shop');
                controlsQuery.mainGrd.$grdId.jqGrid("clearGridData");
                for(var i=0;i<outObj.box_cnt;i++){
                	if (oary[i].bnk_flg == "2") {
                		if (oary[i].prd_admin_flg && ((oary[i].prd_admin_flg).substr(0,1)) == "Y"){
                			rowDatas.push(oary[i]);
                		}
                	}else {
                		rowDatas.push(oary[i]);
                	}
                }
                setGridInfo(rowDatas, "#ppboxInfoGrd");
            }
            return true;
        },
        //Clear
        clear_func : function(){
            toolFunc.clearInput();
            controlsQuery.mainGrd.$grdId.jqGrid("clearGridData");
            controlsQuery.woInfoGrd.$grdId.jqGrid("clearGridData");
        },
        //Out
        wo_out_func : function(){
            "use strict";
            var inObj,
                outObj,
                wo_info_grid,
                box_info_grid,
                dn_no,
                dnno,
                relate_usr,
                palte_no,
                remark,
                iary = [],
                iaryC=[],
                iary1 = [],
                ids,
                idn,
                i,
                j,
                box_cnt,
                dn_cnt,
                hasGK = false,
                hasLX = false,
                gkBox_id,
                lzBox_id,
                date,
                time,
                evt_seq_id,
                rowData,
                rowDataC,
                warnMsg = "";
            var acnt=0;
          //  var action_flg='A';
         //   var boxallcnt = 0;
        //    var dnleftcnt = 0;
            box_info_grid = controlsQuery.mainGrd.$grdId;
            wo_info_grid =controlsQuery.woInfoGrd.$grdId;
            dnno = controlsQuery.$DNNoSelect.val();
            var dninfo = new Array();
            dninfo = dnno.split("@");
            dn_no = dninfo[0];
            evt_seq_id = dninfo[1];
            relate_usr = controlsQuery.$trxUserInput.val().trim();
            palte_no = controlsQuery.$palteNOInput.val().trim();
            remark = controlsQuery.$remarkInput.val().trim();
            
            if(!dn_no){
                showErrorDialog("","请添加交货订单号");
                return false;
            }
            if(!relate_usr){
                showErrorDialog("","请输入承运人");
                return false;
            }
            if(!palte_no){
                showErrorDialog("","请输入车牌号");
                return false;
            }
            ids = box_info_grid.jqGrid("getGridParam","selarrrow");
            box_cnt = ids.length;
            if( box_cnt === 0 ){
                showErrorDialog("","请勾选需要出货的箱号。");
                return false;
            }
            for( i = 0; i < box_cnt; i++ ){
            //	var errflg="YES";
            //	var expflg = "YES";
            	rowData = box_info_grid.jqGrid('getRowData', ids[i]);
//                if(i>1){
//                    for(var a=0; a<iary1.length;a++){
//                        if(iary1[a].pallet_id==rowData['pallet_id_fk']){
//                        	expflg = "NO"
//                        	break;
//                        }
//                    }
//                }
//                if(expflg=="YES"){
//                  iary1.push({
//                    pallet_id : rowData['pallet_id_fk']
//                  });
//                }
//            	if(gDestoutObj.tbl_cnt>1){
//            		for(var d=0;d<gDestoutObj.tbl_cnt;d++){
//            			if(gDestoutObj.oary[d].data_id!=rowData['dest_shop_dsc']){
//            				continue;
//            			}else{
//            				errflg="NO";
//            			}
//            		}
//            		if(errflg=="YES"){
//            			showErrorDialog("","您没有操作箱子所属仓位的权限！");
//                        return false;
//            		}
//            	}else{
//            		if(gDestoutObj.oary.data_id!=rowData['dest_shop_dsc']){
//            			showErrorDialog("","您没有操作箱子所属仓位的权限！");
//            			return false;
//            		}  
//            	}
               	if(rowData.pallet_id_fk==""){
           		 showErrorDialog("","箱子[" + rowData.box_id + "]还未打包，不能出货" );
                    return false;
             	}
             	//客户ID
                var cusId = rowData.cus_id;
             //   boxallcnt = boxallcnt + parseInt(rowData['prd_qty'], 10);
                iary.push({
                    box_id : rowData['box_id']
                });
                //Check GK * LZ
                if( false === hasGK &&
                    0 != parseInt(rowData['gk_cnt'], 10) ){
                    hasGK = true;
                    gkBox_id = rowData['box_id'];
                    warnMsg += "箱子["+ gkBox_id +"]中有管控品！";
                }
                if( false === hasLX &&
                    0 != parseInt(rowData['lz_cnt'], 10) ){
                    hasLX = true;
                    lzBox_id = rowData['box_id'];
                    warnMsg += "箱子["+ lzBox_id +"]中有留滞品！";
                }
            }
               
            idn = wo_info_grid.jqGrid("getGridParam","selarrrow");
            dn_cnt = idn.length;
            if( dn_cnt === 0 ){
                showErrorDialog("","请勾选需要出货的交货订单。");
                return false;
            }
            for( j = 0; j < dn_cnt; j++ ){
            //	var errflg="YES";
            	rowDataC = wo_info_grid.jqGrid('getRowData', idn[j]);
            	iaryC.push({
            		dn_no : rowDataC['dn_no'],
                    evt_seq_id:rowDataC['evt_seq_id'],
                    plan_timestamp:rowDataC['plan_timestamp']
                });
           // 	dnleftcnt = dnleftcnt + parseInt(rowDataC['left_cnt'], 10);
            }
            if(j>1){
            	iaryC.sort(function(x, y){
            		if(x.plan_timestamp < y.plan_timestamp){
                        return -1;
                    }else if(x.plan_timestamp > y.plan_timestamp){
                        return 1;
                    }else{
                        return 0;
                    }
            	});	
            }
//            if(!_isDnFirst){
//            	action_flg='D';
//                if(boxallcnt>dnleftcnt){
//                    showErrorDialog("","出货玻璃数量大于交货订单剩余交货数量！");
//                    return false;
//                }
//            }
            inObj = {
            	trx_id      : VAL.T_XPWMSOPE,
                action_flg  : 'A'           ,
                evt_user    : VAL.EVT_USER,//将发料人员改为登陆人员
                dn_no       : dn_no,
                relate_usr  : relate_usr,
                palte_no    : palte_no,
                remark      : remark,
                box_cnt     : box_cnt,
                dn_cnt      : dn_cnt,
                slot_chk_flg : "Y",
                date        : date,
                time        : time,
                evt_seq_id  :evt_seq_id,
                iary         : iary,
                iaryC        :iaryC
            };
//            if(action_flg=='D'){
//            	inObj.wo_id = controlsQuery.$DNNoSp.text();
//            }
            if( true === hasGK ||
                true === hasLX){
                showWarnningDialog({
                    errMsg  : warnMsg + "是否继续?",
                    callbackFn : function(data) {
                        if(data.result === true){
                            outObj = comTrxSubSendPostJson(inObj);
                            if(outObj.rtn_code == VAL.NORMAL){
                                showSuccessDialog("出货成功！");
                                //业务逻辑变更，出货时多个栈板，导出逻辑待确认。
//                                if(outObj.export_flg == "Y"){
//                                	btnFunc.exportPalletInfo(pallet_id);
//                                }
                                if(cusId == "006"){
                                    var inObj1 = {
                                        trx_id      : VAL.T_XPWMSOPE,
                                        action_flg  : "Z",
                                        pallet_id   : rowData.pallet_id_fk
                                    };
                                    var outObj1 = comTrxSubSendPostJson(inObj1);
                                    if(outObj1.rtn_code == VAL.NORMAL){
                                        showMessengerSuccessDialog("成功导出资料！",1);
                                    }
                                }
                               try{
                               	toolFunc.printPallet(iary);
                               }catch(ex){
                               	showMessengerErrorDialog("栈板标签打印失败!",1);
                               	console.error(ex);
                               }
                               for(var b=0; b<iary1.length;b++){
                               	btnFunc.exportPalletInfo(iary1[b].pallet_id);
                               }
                               // controlsQuery.woInfoGrd.$grdId.jqGrid("clearGridData");
                           	 //	controlsQuery.$DNNoSp.text("");
                           	    controlsQuery.$palletIDInput.val("");
                           	   controlsQuery.$phypalletIDInput.val("");
                            }
                        }
                    }
                });
            }else{
                outObj = comTrxSubSendPostJson(inObj);
                if(outObj.rtn_code == VAL.NORMAL){
                    showSuccessDialog("出货成功！");
                    //业务逻辑变更，出货时多个栈板，导出逻辑待确认。
//                    if(outObj.export_flg == "Y"){
//                    	btnFunc.exportPalletInfo(pallet_id);
//                    }
                    if(cusId == "006"){
                        var inObj1 = {
                            trx_id      : VAL.T_XPWMSOPE,
                            action_flg  : "Z",
                            pallet_id   : $("#palletIDInput").val()
                        };
                        var outObj1 = comTrxSubSendPostJson(inObj1);
                        if(outObj1.rtn_code == VAL.NORMAL){
                            showMessengerSuccessDialog("成功导出资料！",1);
                        }
                    }
                   try{
                   	toolFunc.printPallet(iary);
                   }catch(ex){
                   	showMessengerErrorDialog("栈板标签打印失败!",1);
                   	console.error(ex);
                   }
                   for(var b=0; b<iary1.length;b++){
                   	btnFunc.exportPalletInfo(iary1[b].pallet_id);
                   }
                   // controlsQuery.woInfoGrd.$grdId.jqGrid("clearGridData");
               	 	//controlsQuery.$DNNoSp.text("");
               	    controlsQuery.$palletIDInput.val("");
              	    controlsQuery.$phypalletIDInput.val("");
                }
            }
            return true;
        },
        pack_func: function(){
            var inObj,
                outObj,
                box_info_grid,
                pallet_id,
                phypallet_id,
                iary = [],
                ids,
                i,
                box_cnt,
                rowData,
                cus_id,
                pnl_cnt=0;
        	cus_id = controlsQuery.$vdrIDSelect.val();
            box_info_grid = controlsQuery.mainGrd.$grdId;
            pallet_id = controlsQuery.$palletIDInput.val().trim();
            phypallet_id = controlsQuery.$phypalletIDInput.val().trim();
            
          	if(!cus_id){
        		showErrorDialog('001','请选择客户代码！');
                return false;
        	}
            /*if(!pallet_id){
            	  showErrorDialog("","栈板号不能为空");
                  return false;
            }*/
            if(cus_id=="007"){
                if(!phypallet_id){
                    showErrorDialog("","物理栈板号不能为空");
                    return false;
                }
            }
            ids = box_info_grid.jqGrid("getGridParam","selarrrow");
            box_cnt = ids.length;
            if( box_cnt === 0 ){
                showErrorDialog("","请勾选需要打包的箱号。");
                return false;
            }
            for( i = 0; i < box_cnt; i++ ){
            	rowData = box_info_grid.jqGrid('getRowData', ids[i]);
            	if(rowData.pallet_id_fk!=""){
            		 showErrorDialog("","箱子[" + rowData.box_id + "]已经打包，请先取消" );
                     return false;
            	}
            	pnl_cnt += parseInt(rowData['prd_qty'], 10);
                iary.push({
                    box_id : rowData['box_id'],
                    mdl_id_fk : rowData['final_mdl']
                });
            }
               
            inObj = {
            	trx_id      : VAL.T_XPWMSOPE,
                action_flg  : 'P',
                evt_user    : VAL.EVT_USER,
                pallet_id   : pallet_id,
                phypallet_id   : phypallet_id,
                box_cnt     : box_cnt,
                cus_id      : cus_id,
                iary         : iary,
            };
            btnQuery.$unpack_btn.showCallBackWarnningDialog({
          	errMsg : "已选中" + box_cnt + "个箱子，共"+pnl_cnt+"片玻璃，是否继续打包?",
              callbackFn : function(data) {
          	   if(data.result){
          	       outObj = comTrxSubSendPostJson(inObj);
                   if(outObj.rtn_code == VAL.NORMAL){
                       showMessengerSuccessDialog("打包成功!",1);
                       if(isArray(outObj.table)){
                            pallet_id = outObj.table[0].pallet_id_fk;
                       }else{
                            pallet_id =outObj.table.pallet_id_fk;
                       }

                       for( j = 0; j < box_cnt; j++ ){
                       	rowData = box_info_grid.jqGrid('getRowData', ids[j]);
                       	rowData['pallet_id_fk'] =  pallet_id;
                       	box_info_grid.jqGrid('setRowData', ids[j], rowData);
                       }
                       controlsQuery.$phypalletIDInput.val("");
                   }          	   
                  }
              }
          });
     
        },
        unpack_func: function(){
            var inObj,
                outObj,
                box_info_grid,
                iary = [],
                ids,
                i,
                box_cnt,
                rowData,
                cus_id;
            
            box_info_grid = controlsQuery.mainGrd.$grdId;
            
            ids = box_info_grid.jqGrid("getGridParam","selarrrow");
            box_cnt = ids.length;
            if( box_cnt === 0 ){
                showErrorDialog("","请勾选需要取消打包的箱号。");
                return false;
            }
            for( i = 0; i < box_cnt; i++ ){
            	rowData = box_info_grid.jqGrid('getRowData', ids[i]);
            	if(rowData.pallet_id_fk==""){
            		 showErrorDialog("","箱子[" + rowData.box_id + "]还未打包" );
                     return false;
            	}
                iary.push({
                    box_id : rowData['box_id']
                });
            }
               
            inObj = {
            	trx_id      : VAL.T_XPWMSOPE,
                action_flg  : 'U',
                evt_user    : VAL.EVT_USER,
                box_cnt     : box_cnt,
                iary         : iary,
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
            	showMessengerSuccessDialog("取消打包成功!",1);
                btnFunc.query_func();
            }
        },
//        exportPalletInfo : function(pallet_id){
//        	var inObj = {
//            	trx_id      : VAL.T_XPWMSOPE,
//                action_flg  : "E",
//                pallet_id   : pallet_id
//            };
//        	var outObj = comTrxSubSendPostJson(inObj);
//        	if(outObj.rtn_code == VAL.NORMAL){
//        		showMessengerSuccessDialog("成功导出资料！",1);
//        	}
//        },
        //Add wo
        real_add_wo : function(inObj, dn_id){
            var i,
                undn,
                plantime,
                date,
                time,
                time1,
                getDnInfoInObj,
                getDnInfoOutObj,
                dn_wh_out_prd_qty = 0,
                dnAry = [];
            dnid = controlsQuery.$DNNoSelect.val();
            if(!dnid){
               showErrorDialog('P4400-102','交货订单号不能为空!');
               return false;
            }
            var dninfo = new Array();
            dninfo = dnid.split("@");
            //undn = dninfo[1];
            //plantime = dninfo[2];
            //var datetimeinfo = new Array();
            //datetimeinfo = plantime.split(" ");
            //date = datetimeinfo[0];
            //time1 = datetimeinfo[1];
            //var time1info = new Array();
            //time1info = datetimeinfo[1].split(".");
            //time = time1info[0];
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                //Get Dn info
                getDnInfoInObj = {
                    trx_id      : VAL.T_XPAPLYDN,
                    action_flg  : 'Q'           ,
                    iary        : {
                        dn_no    : dn_id || controlsQuery.$DNNoSp.text(),
                        wo_id_fk : controlsQuery.$woIdSelect.val()
                       // date     : date,
                       // time     : time
                    }
                };
                getDnInfoOutObj = comTrxSubSendPostJson(getDnInfoInObj);
                if (getDnInfoOutObj.rtn_code == VAL.NORMAL) {
                	if(1 === parseInt(getDnInfoOutObj.tbl_cnt, 10)){
                		dnAry.push(getDnInfoOutObj.oary);
                	}if(1 < parseInt(getDnInfoOutObj.tbl_cnt, 10)){
                		dnAry = getDnInfoOutObj.oary;
                	}
                	if(dnAry[0].dn_stat=="完成"){
                		showErrorDialog('P4400-102','交货订单已完成，请勿添加!');
                		return false;
                	}
                	outObj.oary.dn_no = dn_id || controlsQuery.$DNNoSp.text();
                	outObj.oary.dn_ship_qty = dnAry[0].ship_qty;
                	outObj.oary.dn_wh_out_prd_qty = dnAry[0].dn_wh_out_prd_qty;
                	outObj.oary.evt_seq_id = dnAry[0].evt_seq_id;
                	outObj.oary.plan_timestamp = plantime; 
                	outObj.oary.diff_qty = parseInt(outObj.oary.pln_prd_qty, 10) - parseInt(outObj.oary.wh_out_prd_qty, 10);
                	outObj.oary.left_cnt = parseInt(dnAry[0].ship_qty, 10) - parseInt(dnAry[0].dn_wh_out_prd_qty, 10);
                	controlsQuery.woInfoGrd.$grdId.jqGrid ('addRowData', $.jgrid.randId(), outObj.oary);
            		if(dn_id){
            			controlsQuery.$DNNoSp.text(dn_id);
            		}
//                	if(_isDnFirst){
//                		if(dn_id){
//                			controlsQuery.$DNNoSp.text(dn_id);
//                		}
//                	}else{
//                        controlsQuery.$DNNoSp.text(inObj.iary.wo_id);
//                	}
                }
            }
        },
        add_wo_func : function(){
            var i,
                j,
                x,
                inObj,
                wo_id,
                dn_id,
                dnid,
                undn,
                pro,
                first_dn_id,
                first_wo_id,
                wo_info_grid,
                wo_info_grid_ids,
                prepreerence_dn_id,
                prepreerence_wo_id,
                inObj1,
                outObj1,
                dnno1,
                unid,
                iary = {};
            wo_info_grid = controlsQuery.woInfoGrd.$grdId;
            var dninfo1 = new Array();
            wo_id = controlsQuery.$woIdSelect.val();
            if(!wo_id){
                showErrorDialog('P4400-101','内部订单号不能为空！');
                return false;
            }
            dnid = controlsQuery.$DNNoSelect.val();
            if(!dnid){
                showErrorDialog('P4400-102','交货订单号不能为空!');
                return false;
            }
            //dn与wo需绑定
            var dninfo = new Array();
            dninfo = dnid.split("@");
            dn_id = dninfo[0];
            //undn = dninfo[1];
            //pro = dninfo[3];
//            iary.wo_id_fk = wo_id;
//            iary.dn_no = dn_id;
//            inObj1 = {
//                trx_id      : VAL.T_XPAPLYDN,
//                action_flg  : 'Q'           ,
//                iary        : iary
//            };
//            outObj1 = comTrxSubSendPostJson(inObj1);
//            if (outObj1.rtn_code == VAL.NORMAL){
//            	if(outObj1.oary==undefined){
//            		showErrorDialog('','DN与内部订单需绑定！');
//            		return false;
//            	}
//            }else{
//            	return false;
//            }
         //   if(_isDnFirst){
            	first_dn_id = controlsQuery.$DNNoSp.text();
                //不能混DN
                if (first_dn_id) {
                    if (dn_id !== first_dn_id) {
                        showErrorDialog('P4400-103', '当前选择的交货订单号[' + dn_id +
                            ']和已经登记的交货订单号[' + first_dn_id + ']不同，不允许混交货订单，请确认！');
                        return false;
                    }
                }else{
                    controlsQuery.mainGrd.$grdId.jqGrid("clearGridData");
                }
                //不能有重复WO
                wo_info_grid_ids = wo_info_grid.jqGrid('getDataIDs');
                if(wo_info_grid_ids.length > 0){
                    for(i = wo_info_grid_ids.length -1; i >= 0; i--){
                        if(wo_id == wo_info_grid.jqGrid('getRowData', wo_info_grid_ids[i])['wo_id']){
                            showErrorDialog('P4400-104','内部订单' + wo_id + '已经添加，请勿重复添加！');
                            return false;
                        }
                    }
                }
                inObj = {
                    trx_id      : VAL.T_XPAPLYWO,
                    action_flg  : 'Q'           ,
                    iary        : {
                        wo_id : wo_id
                    }
                };
                prepreerence_wo_id = (document.getElementById('woIdSelect').options)[1].value;
                btnFunc.real_add_wo(inObj, first_dn_id ? null : dn_id);
//            }else{
//            	first_wo_id = controlsQuery.$DNNoSp.text();
//                if (first_wo_id) {
//                    if (wo_id !== first_wo_id) {
//                        showErrorDialog('P4400-103', '当前选择的交货订单号[' + wo_id +
//                            ']和已经登记的交货订单号[' + first_wo_id + ']不同，不允许混交货订单，请确认！');
//                        return false;
//                    }
//                }else{
//                    controlsQuery.mainGrd.$grdId.jqGrid("clearGridData");
//                }
//                //不能有重复WO
//                wo_info_grid_ids = wo_info_grid.jqGrid('getDataIDs');
//                if(wo_info_grid_ids.length > 0){
//                    for(i = wo_info_grid_ids.length -1; i >= 0; i--){
//                        if(undn == wo_info_grid.jqGrid('getRowData', wo_info_grid_ids[i])['evt_seq_id']){
//                            showErrorDialog('P4400-104','交货订单' + dn_id + '已经添加，请勿重复添加！');
//                            return false;
//                        }
//                    }
//                }
//                //优先级判断
//                var pro_flg = 0;
//                for(j=1;j<pro;j++){
//                	if(pro_flg==1){
//                		break;
//                	}
//                    dnno1=(document.getElementById('DNNoSelect').options)[j].value;
//                	dninfo1 = dnno1.split("@");
//                    unid =  dninfo1[1];
//                    if(wo_info_grid_ids.length > 0){
//                        for(x = 0; x < wo_info_grid_ids.length; x++){
//                            if(unid == wo_info_grid.jqGrid('getRowData', wo_info_grid_ids[x])['evt_seq_id']){
//                            	pro_flg = 0;
//                                break;
//                            }else{
//                            	pro_flg = 1;
//                            }
//                        }
//                    }
//                }
//                if(wo_info_grid_ids.length==0&&pro!=1){
//                	pro_flg = 1;
//                }
//                //end
//                inObj = {
//                        trx_id      : VAL.T_XPAPLYWO,
//                        action_flg  : 'Q'           ,
//                        iary        : {
//                            wo_id : wo_id
//                        }
//                };
//                if(pro_flg ==1){
//                    showWarnningDialog({
//                        errMsg  : '当前内部订单对应多个不同交货订单，有优先级更高订单，请确认是否执行!',
//                        callbackFn : function(data) {
//                            if(data.result === true){
//                            	btnFunc.real_add_wo(inObj, dn_id);
//                            }
//                        }
//                    });
//                }else{
//                	btnFunc.real_add_wo(inObj, dn_id);
//                }   
//            }  
            return true;
        },
        //Delete selected wo
        del_wo_func : function(){
            var i,
                wo_info_grid,
                selectRowIds,
                selectRowIdsLen;
            wo_info_grid = controlsQuery.woInfoGrd.$grdId;
            selectRowIds = wo_info_grid.jqGrid('getGridParam','selarrrow');
            selectRowIdsLen = selectRowIds.length;
            if(selectRowIdsLen <= 0){
                console.warn('Selected row count %s', selectRowIdsLen);
                return false;
            }
            for( i = selectRowIdsLen-1; i>=0; i-- ){
                wo_info_grid.jqGrid('delRowData', selectRowIds[i]);
            }
            controlsQuery.$DNNoSp.text("");
            return true;
        }
//        auto_pallet_func : function(){
//        	var inObj,outObj,crTime,crYear,crMonth,crDay,key;
//        	var cus_id = controlsQuery.$vdrIDSelect.val();
//        	if(!cus_id){
//        		showErrorDialog('001','请选择客户代码！');
//                return false;
//        	}
//        	if(cus_id == "007"){
//        		var wo_id = controlsQuery.$woIdSelect.val();
//        		if(!wo_id){
//            		showErrorDialog('002','请选择内部工单！');
//                    return false;
//        		}
//        		inObj = {
//         			 trx_id : "XPCRTNO",
//       				 action_flg : "7",
//       				 wo_id : wo_id
//                };
//           	    outObj = comTrxSubSendPostJson(inObj);
//                if(outObj.rtn_code == VAL.NORMAL){
//               	   controlsQuery.$palletIDInput.val(outObj.pallet_id);
//                }
//        	}else if(cus_id == "003"){
//        		var pallet003,dg="U",nx="P";
//        		var wo_id = controlsQuery.$woIdSelect.val();
//        		if(!wo_id){
//            		showErrorDialog('002','请选择内部工单！');
//                    return false;
//        		}
//        	    var inTrxObjWo = {
//        	    	        trx_id: 'XPINQWOR',
//        	    	        action_flg: 'I',
//        	    	        worder_id: wo_id
//        	    	 };
//        	     var outTrxObjWo = comTrxSubSendPostJson(inTrxObjWo);
//        	     if(outTrxObjWo.rtn_code == "0000000") {
//        	    	 if(outTrxObjWo.mdl_cate_fk.indexOf("C") > 0 ){
//        	    		 dg = "W";
//        	    		 nx = "B";
//                     }
//        	     }
//             	crTime = new Date();
//            	crYear = crTime.getFullYear();
//            	crYear = crYear.toString();
//                crMonth = crTime.getMonth() + 1;
//                if(crMonth==10){
//                	crMonth = "A";
//                }else if(crMonth==11){
//                	crMonth = "B";
//                }else if(crMonth==12){
//                	crMonth = "C";
//                }
//    
//        	    pallet003 = "E" + dg + nx + "S" + "A" + crYear.substring(3,4) + crMonth;
//        	    key = crYear + crMonth;
//             	inObj = {
//         		     trx_id : "XPCRTNO",
//       				 action_flg : "3",
//       				 key_id : key,
//       				 type : "3"
//                 };
//           	    outObj = comTrxSubSendPostJson(inObj);
//                if(outObj.rtn_code == VAL.NORMAL){
//               	    controlsQuery.$palletIDInput.val(pallet003 + outObj.serial_no);
//                }
//
//        	}else{//其他客户
//            	crTime = new Date();
//            	crYear = crTime.getFullYear();
//            	crYear = crYear.toString();
//                crMonth = crTime.getMonth() + 1;
//                if(crMonth<10){
//                	crMonth = "0" + crMonth;
//                }
//            	crDay = crTime.getDate();
//            	if(crDay<10){
//            		crDay = "0" + crDay;
//            	}
//            	key = crYear+crMonth+crDay;
//                //alert(crYear+crMonth+crDay);
//            	inObj = {
//          				 trx_id : "XPCRTNO",
//        				 action_flg : "A",
//        				 key_id : key,
//        				 type : "W"
//                        };
//            	outObj = comTrxSubSendPostJson(inObj);
//                if(outObj.rtn_code == VAL.NORMAL){
//                	controlsQuery.$palletIDInput.val(key+outObj.serial_no);
//                }
//        	}
//        }

    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.$query_btn.click(function(){
            btnFunc.query_func();
        });
        btnQuery.$clear_btn.click(function(){
            btnFunc.clear_func();
        });
        btnQuery.$wh_out_btn.click(function(){
            btnFunc.wo_out_func();
        });
        btnQuery.$addWoBtn.click(function(){
            btnFunc.add_wo_func();
        });
        btnQuery.$del_wo_btn.click(function(){
            btnFunc.del_wo_func();
        });
//        btnQuery.$autobtn.click(function(){
//            btnFunc.auto_pallet_func();
//        });
        btnQuery.$pack_btn.click(function(){
            btnFunc.pack_func();
        });
        btnQuery.$unpack_btn.click(function(){
            btnFunc.unpack_func();
        });
    };

    var shortCutKeyBind = function(){
        document.onkeydown = function(event) {
            if(event.keyCode == F1_KEY){
                btnQuery.$query_btn.click();
                return false;
            }else if(event.keyCode == F2_KEY){
                btnQuery.$clear_btn.click();
                return false;
            }else if(event.keyCode == F3_KEY){
                btnQuery.$wh_out_btn.click();
                return false;
            }else if(event.keyCode == F4_KEY){
                btnQuery.$del_wo_btn.click();
                return false;
            }
            return true;
        };
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var woInfoGrdCM = [
            {name: 'dn_no'            , index: 'dn_no'            , label: DN_NO_TAG , width: DN_NO_CLM},
            {name: 'dn_ship_qty'      , index: 'dn_ship_qty'      , label: '计出数' , width: QTY_CLM},
            {name: 'dn_wh_out_prd_qty', index: 'dn_wh_out_prd_qty', label: '实出数' , width: QTY_CLM},
            {name: 'left_cnt', index: 'left_cnt', label: '剩余数' , width: QTY_CLM},
            {name: 'wo_id'            , index: 'wo_id'            , label: WO_ID_TAG , width: WO_ID_CLM},
            {name: 'pln_prd_qty'      , index: 'pln_prd_qty'      , label: '计划数' , width: QTY_CLM},
            {name: 'wh_out_prd_qty'   , index: 'wh_out_prd_qty'   , label: '出库数' , width: QTY_CLM},
            {name: 'diff_qty'         , index: 'diff_qty'         , label: '差异数' , width: QTY_CLM},
            {name: 'act_stb_timestamp', index: 'act_stb_timestamp', label: '下线日期' , width: TIMESTAMP_CLM},
            {name: 'cus_id_fk'        , index: 'cus_id_fk'        , label: CUS_ID_TAG , width: CUS_ID_CLM},
            {name: 'mdl_id'           , index: 'mdl_id'           , label: MDL_ID_TAG , width: MDL_ID_CLM},
            {name: 'evt_seq_id'       , index: 'evt_seq_id'           , label: MDL_ID_TAG , width: MDL_ID_CLM,hidden:true},
            {name: 'plan_timestamp'   , index: 'plan_timestamp'           , label: MDL_ID_TAG , width: MDL_ID_CLM,hidden:true}
        ];
        controlsQuery.woInfoGrd.$grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            width: domObj.$woInfoGrdDiv.width(),
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:200,
            loadonce:true,
            multiselect : true,
            viewrecords:true,
            pager : controlsQuery.woInfoGrd.grdPg,
            fixed: true,
            colModel: woInfoGrdCM
        });

        var mainGrdCM = [
            {name: 'cus_id',         index: 'cus_id',           label: CUS_ID_TAG      ,   width: CUS_ID_CLM},
            {name: 'is_wip_in',      index: 'is_wip_in',        label: '半成品'         ,     width: IS_WIP_IN_CLM},
            {name: 'so_id',          index: 'so_id',            label: SO_NO_TAG       ,    width: WO_ID_CLM},
            {name: 'wo_id',          index: 'wo_id',            label: WO_ID_TAG       ,    width: WO_ID_CLM},
            {name: 'box_id',         index: 'box_id',           label: CRR_ID_TAG      ,    width: BOX_ID_CLM},
            {name: 'ship_box_id',   index: 'ship_box_id',   label: "出货箱号"   , width: BOX_ID_CLM},
            {name: 'lot_id',         index: 'lot_id',           label: LOT_ID_TAG      ,    width: LOT_ID_CLM},
            {name: 'pallet_id_fk',   index: 'pallet_id_fk',     label: "栈板"      ,    width: LOT_ID_CLM},
           // {name: 'ext_11',         index: 'ext_11',           label: "物理栈板"      ,    width: LOT_ID_CLM},
            {name: 'wh_in_timestamp',index: 'wh_in_timestamp',  label: WH_IN_TIMESTAMP_TAG, width: LOT_ID_CLM},
            {name: 'relate_usr',     index: 'relate_usr',       label: '送货人'      ,        width: LOT_ID_CLM},
            {name: 'evt_usr',        index: 'evt_usr',          label: EVT_USR      ,       width: LOT_ID_CLM},
            {name: 'prd_qty',        index: 'prd_qty',          label: TOTAL_QTY_TAG   ,    width: QTY_CLM },
            {name: 'mtrl_prod_id',   index: 'mtrl_prod_id',     label: FROM_MTRL_ID_TAG   , width: MTRL_PROD_ID_CLM},
            {name: 'mdl_id_fk',      index: 'mdl_id_fk',        label: TO_MTRL_ID_TAG     , width: MDL_ID_CLM},
            {name: 'fm_mdl_id_fk',   index: 'fm_mdl_id_fk',     label: FM_MDL_ID_TAG      , width: MDL_ID_CLM},
            {name: 'cut_mdl_id_fk',  index: 'cut_mdl_id_fk',    label: CUT_MDL_ID_TAG     , width: MDL_ID_CLM},
            {name: 'final_mdl',      index: 'final_mdl',         label: "成品型号"           , width: MDL_ID_CLM,hidden : true},
            {name: 'from_thickness', index: 'from_thickness',   label: FROM_THICKNESS_TAG , width: QTY_CLM},
            {name: 'to_thickness',   index: 'to_thickness',     label: TO_THICKNESS_TAG   , width: QTY_CLM},
            {name: 'box_fst_yield',  index: 'box_fst_yield',    label: PROC_YIELD_TAG   ,   width: QTY_CLM},
            {name: 'box_snd_yield',  index: 'box_snd_yield',    label: WHOLE_YIELD_TAG  ,   width: QTY_CLM},
            {name: 'dest_shop' ,     index: 'dest_shop' ,       label: DEST_SHOP_TAG    ,   width: DEST_SHOP_CLM },
            {name: 'dest_shop_dsc',  index: 'dest_shop_dsc',    label: DEST_SHOP_TAG    ,   hidden : true},
            {name: 'box_weight',     index: 'box_weight',       label: WEIGHT_TAG       ,   width: QTY_CLM },
            {name: 'box_stat'  ,     index: 'box_stat'  ,       label: STATUS_TAG       ,   width: PRD_STAT_CLM},
            {name: 'ok_cnt',         index: 'ok_cnt',           label: OK_CNT_TAG       ,   width: QTY_CLM },
            {name: 'ng_cnt',         index: 'ng_cnt',           label: NG_CNT_TAG       ,   width: QTY_CLM },
            {name: 'sc_cnt',         index: 'sc_cnt',           label: SC_CNT_TAG       ,   width: QTY_CLM },
            {name: 'gk_cnt',         index: 'gk_cnt',           label: GRADE_CONTROL_TAG,   width: QTY_CLM },
            {name: 'lz_cnt',         index: 'lz_cnt',           label: GRADE_SCRP_TAG   ,   width: QTY_CLM }
        ];
        controlsQuery.mainGrd.$grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:250,
            width: domObj.$ppboxInfoGrdDiv.width(),
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:200,
            loadonce:true,
            multiselect : true,
            viewrecords:true,
            pager : controlsQuery.mainGrd.grdPg,
            fixed: true,
            colModel: mainGrdCM
        });
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });
        //Click radio
//        $('input[name=dnwoPriorityRadios]').click(function(){
//            toolFunc.dnwoPriorityRadiosClick();
//        });
        //Filter box id in grid
        controlsQuery.$ppBoxIDInput.keydown(function(event){
            'use strict';
            var hasFind,
                box_id;
            if(event.keyCode === 13){

                var i, j,
                    grd,
                    hasFound,
                    curRowData,
                    curRowElement,
                    box_id,
                    rowIds,
                    out_box_id,
                    scrollHeight = 0;

                hasFound = false;

                box_id = $.trim(controlsQuery.$ppBoxIDInput.val());
                if(!box_id){
                    showErrorDialog("","请输入箱号ID");
                    return false;
                }
                grd = controlsQuery.mainGrd.$grdId;

                rowIds = grd.jqGrid('getDataIDs');
                if(rowIds){
                	$("#wipInfoGrd tr").removeClass('bg-found').addClass('ui-widget-content');
                    for(i = 0, j = rowIds.length; i < j; i++) {
                        curRowElement = $("#" + rowIds[i]);
                        curRowData = grd.jqGrid('getRowData', rowIds[i]);
                        if( !hasFound && curRowData['box_id'] == box_id){
                           //grd.trigger("reloadGrid");
                            //curRowElement.removeClass('ui-widget-content').addClass('bg-found');
                            if($("#" + curRowElement[0].children[0].children[0].id).attr("checked")!="checked"){
                            grd.jqGrid('setSelection',rowIds[i]);
                            }
                            hasFound = true;
                            //scroll
                            scrollHeight = (curRowElement[0].rowIndex-1) * curRowElement.height();
                            $($('div.ui-jqgrid-bdiv')[1]).scrollTop(scrollHeight);
               			
                			controlsQuery.$ppBoxIDInput.val("");
                            break;
                        }
                    }
                    if(!hasFound){
                        showErrorDialog("", "["+ box_id +"]不在列表中！");
                        return false;
                    }
                }
            }
            return true;
        });
        
        controlsQuery.$palletIDInput.keydown(function(event) {
        	if(event.keyCode === 13){
        		return false;
        	}
        });
        
       controlsQuery.$phypalletIDInput.keydown(function(event) {
       	if(event.keyCode === 13){
       		return false;
       	}
       });
        controlsQuery.$shipboxInput.keydown(function(event){
            'use strict';
            var hasFind;
            if(event.keyCode === 13){
            	var i, j,
                grd,
                hasFound,
                curRowData,
                curRowElement,
                box_id,
                rowIds,
                out_box_id,
                scrollHeight = 0;

            hasFound = false;

            var ship_box_id = $.trim(controlsQuery.$shipboxInput.val());
            if(!ship_box_id){
                showErrorDialog("","请输入出货箱号!");
                return false;
            }
            grd = controlsQuery.mainGrd.$grdId;

            rowIds = grd.jqGrid('getDataIDs');
            if(rowIds){
            	$("#wipInfoGrd tr").removeClass('bg-found').addClass('ui-widget-content');
                for(i = 0, j = rowIds.length; i < j; i++) {
                    curRowElement = $("#" + rowIds[i]);
                    curRowData = grd.jqGrid('getRowData', rowIds[i]);
                    if( !hasFound && curRowData['ship_box_id'] == ship_box_id){
                       //grd.trigger("reloadGrid");
                        //curRowElement.removeClass('ui-widget-content').addClass('bg-found');
                        if($("#" + curRowElement[0].children[0].children[0].id).attr("checked")!="checked"){
                        grd.jqGrid('setSelection',rowIds[i]);
                        }
                        hasFound = true;
                        //scroll
                        scrollHeight = (curRowElement[0].rowIndex-1) * curRowElement.height();
                        $($('div.ui-jqgrid-bdiv')[1]).scrollTop(scrollHeight);
           			
            			controlsQuery.$shipboxInput.val("");
                        break;
                    }
                }
                if(!hasFound){
                    showErrorDialog("", "["+ ship_box_id +"]不在列表中！");
                    return false;
                }
            }
            	
            }
            return true;
        });
        
      /*  controlsQuery.$palletIDInput.keydown(function(e) {
        	e.stopPropagation();
        })*/
        
//        controlsQuery.$palletInput.keydown(function(event){
//            'use strict';
//            var hasFind,
//                pallet_id;
//            if(event.keyCode === 13){
//            	pallet_id = controlsQuery.$palletInput.val().trim();
//                hasFind = _findRowInGrid1('ppboxInfoGrdDiv', controlsQuery.mainGrd.$grdId, 'pallet_id_fk', pallet_id);
//                return false;
//            }
//            return true;
//        });
        //Bind select cus id action
        controlsQuery.$vdrIDSelect.change(function(){
        	 toolFunc.setDnIdSelect();
//            if(_isDnFirst){
//                if(this.value){
//                    toolFunc.setDnIdSelect();
//                }
//            }else{
//                if(this.value){
//                   // toolFunc.setSoSIdSelect();
//                    toolFunc.setWoIdSelect();
//                }
//            }
        });
        //Bind select so_id action 
//        controlsQuery.$soSIdSelect.change(function(){
//            if(_isDnFirst){
//                if(this.value){
//                }
//            }else{
//                if(this.value){
//                    toolFunc.setWoIdSelect();
//                }
//            }
//        });
        //Bind select dn id action
        controlsQuery.$DNNoSelect.change(function(){
        	toolFunc.setWoIdSelect(this.value);
//            if(_isDnFirst){
//                if(this.value){
//                    toolFunc.setWoIdSelect(this.value);
//                }else{
//                    controlsQuery.$woIdSelect.empty();
//                }
//            }
        });
        //Bind select wo id action
//        controlsQuery.$woIdSelect.change(function(){
//            if(!_isDnFirst){
//                if(this.value){
//                    toolFunc.setDnIdSelect(this.value);
//                }else{
//                    controlsQuery.$DNNoSelect.empty();
//                }
//            }
//        });
        shortCutKeyBind();
    };

    /**
     * Ini view and data
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();
       // _isDnFirst = true;
      //  controlsQuery.$dnPriorityRadio.attr('checked','checked');
     //   controlsQuery.$soSIDDiv.hide();
        toolFunc.clearInput();
        //Ini data
        toolFunc.iniVdrIDSelect();
        toolFunc.iniuserSelect();
        toolFunc.inipalteSelect();
        toolFunc.setDestShopSel();
        toolFunc.getPrinters();
        //Ini dest id - dest desc
        _destListTool.ini();
    };

    initializationFunc();
    function resizeFnc(){                                                                      
    	var offsetBottom, divWidth;                                                              
    	
		divWidth = domObj.$ppboxInfoGrdDiv.width();                                   
		offsetBottom = domObj.$window.height() - domObj.$ppboxInfoGrdDiv.offset().top;
		domObj.$ppboxInfoGrdDiv.height(offsetBottom * 0.95);                          
		domObj.$ppboxInfoGrd.setGridWidth(divWidth * 0.99);                   
		domObj.$ppboxInfoGrd.setGridHeight(offsetBottom * 0.99); 
		
		divWidth = domObj.$window.width() - domObj.$woInfoGrdDiv.offset().left;                                   
		domObj.$woInfoGrd.setGridWidth(divWidth * 0.99-38); 
		offsetBottom = $("#formDiv").height();
		domObj.$woInfoGrdDiv.height(offsetBottom * 0.99);                          
		domObj.$woInfoGrd.setGridHeight(offsetBottom * 0.99 * 0.6 - 50);
    };  
   // resizeFnc();                                                                               
    domObj.$window.resize(function() {                                                         
    	resizeFnc(); 
	});

    $("#exportCsotShippingDataBtn").click(function(){
        var palletId=$("#palletIDInput").val();
        if(palletId==null||palletId==""){
            showErrorDialog("","请输入栈板ID！");
            return false;
        }
        var inObj = {
            trx_id      : VAL.T_XPWMSOPE,
            action_flg  : "F",
            pallet_id   : $("#palletIDInput").val()
        };
        var outObj = comTrxSubSendPostJson(inObj);
        if(outObj.rtn_code == VAL.NORMAL){
            showMessengerSuccessDialog("成功导出资料！",1);
        }
    });

    $("#exportXmtmShippingDataBtn").click(function(){
    	var inObj = {
            	trx_id      : VAL.T_XPWMSOPE,
                action_flg  : "Z",
                pallet_id   : $("#palletIDInput").val()
            };
        	var outObj = comTrxSubSendPostJson(inObj);
        	if(outObj.rtn_code == VAL.NORMAL){
        		showMessengerSuccessDialog("成功导出资料！",1);
        	}
    });
//    $("#testBtn").click(function(){
//    	var inObj = {
//            	trx_id      : VAL.T_XPWMSOPE,
//                action_flg  : "E",
//                pallet_id   : $("#palletIDInput").val()
//            };
//        	var outObj = comTrxSubSendPostJson(inObj);
//        	if(outObj.rtn_code == VAL.NORMAL){
//        		showMessengerSuccessDialog("成功导出资料！",1);
//        	}
//    });
    
});